<template>
  <div class="total">
    <div class="img">
      <img :src="img" class="image" ref="img" />
    </div>
    <div class="buttom">
      <van-button type="primary" @click="$emit('close')">取消</van-button>
      <van-button type="primary" @click="onComfirm">确定</van-button>
    </div>
  </div>
</template>
<script>
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
import { updateUserPhoto } from '../../../api/user'
export default {
  name: 'HeimaiUpdatePhoto',

  data() {
    return {
      cropper: null
    };
  },
  props: {
    img: {
      type: [String, Object],
      require: true
    }
  },
  mounted() {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false // 关闭默认背景
    })
  },

  methods: {
    onComfirm() {
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        // console.log(blob);
        // 如果接口要求Content-Type是application/json
        // 则传递普通js对象
        // 如果接口要求Content-Type是multipart/form-data
        //  则必须传递FromDate对象
        const formData = new FormData()
        formData.append('photo', blob)
        const { data } = await updateUserPhoto(formData)
        this.$emit('close')
        this.$toast('修改头像成功！')
        this.$emit('update-photo', data.data.photo)
      })
    }
  }
};
</script>

<style lang="less" scoped>
.total {
  width: 100%;
  height: 100%;
  background-color: #000;
}
.img {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}
.image {
  display: block;
  max-width: 100%;
}
/deep/.buttom {
  width: 100%;
  display: flex;
  position: fixed;
  bottom: 0;
  justify-content: space-between;
  color: #fff;
}
</style>